package com.lagou.rpc.provider.server;

import com.lagou.rpc.provider.handler.ImportRpcBeanHandler;
import com.lagou.rpc.provider.handler.RpcServerHandler;
import com.lagou.rpc.zookeeper.handler.RpcRegistryCenter;
import com.lagou.rpc.zookeeper.handler.RpcRegistryCenterFactory;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.net.InetSocketAddress;
import java.util.Map;

/**
 * 启动类
 */
@Service
public class RpcServer implements DisposableBean {

    private NioEventLoopGroup bossGroup;
    private NioEventLoopGroup workerGroup;

    @Autowired
    private  RpcServerHandler rpcServerHandler;


    public void startServer(String ip,int port) {
        try {
            //线程组
            bossGroup = new NioEventLoopGroup(1);
            workerGroup = new NioEventLoopGroup();
            //服务端启动助手
            ServerBootstrap serverBootstrap = new ServerBootstrap();
            serverBootstrap.group(bossGroup,workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel socketChannel) throws Exception {
                            ChannelPipeline pipeline = socketChannel.pipeline();
                            //添加string的编解码器
                            pipeline.addLast(new StringDecoder());
                            pipeline.addLast(new StringEncoder());
                            //业务处理类
                            pipeline.addLast(rpcServerHandler);

                        }
                    });
            ChannelFuture future = serverBootstrap.bind(new InetSocketAddress(ip, port)).sync();
            //自动扫描需要注册的类，并完成注册
            this.registry(ip,port);
            System.out.println("服务端启动成功！");

            future.channel().closeFuture().sync();
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            if (bossGroup!=null){
                bossGroup.shutdownGracefully();
            }
            if (workerGroup!=null){
                workerGroup.shutdownGracefully();
            }
        }
    }

    private void registry(String ip, int port) throws Exception {
        //扫描需要注册的服务
        Map<String, Object> instanceCacheMap = ImportRpcBeanHandler.getInstanceCacheMap();
        //判断
        if (instanceCacheMap.isEmpty()) {
            System.out.println("没有发现需要注册的服务......");
            throw new RuntimeException("没有发现需要注册的服务");
        }

        //获取注册中心
        RpcRegistryCenter rpcRegistryCenter = new RpcRegistryCenterFactory().getObject();
        if(null == rpcRegistryCenter){
            System.out.println("未获取到注册中心");
            throw new RuntimeException("未获取到注册中心");
        }
        //注册到注册中心
        instanceCacheMap.entrySet().stream()
                .forEach(stringObjectEntry -> rpcRegistryCenter.registry(stringObjectEntry.getKey(), ip, port));

    }

    @Override
    public void destroy() throws Exception {
        if (bossGroup!=null){
            bossGroup.shutdownGracefully();
        }
        if (workerGroup!=null){
            workerGroup.shutdownGracefully();
        }
    }
}
